package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTcustContactHistory
 * @Description:华盛证券  根据华盛号（+时间维度查询）客户跟进数据信息 --外部接口
 * @author: chieh
 * @date 2022-12-01 12:30:00
 *
 */

public class aipHSTcustContactHistory implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTcustContactHistory.class);
    String custapiid = getProperty.get("custapiid");
    String custapikey = getProperty.get("custapikey");
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def apiid = inObject.getString("apiid");
            if(custapiid!=apiid){

                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(apiid不匹配),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            def timestamp = inObject.getString("timestamp");
            def sign = inObject.getString("sign");
            def apitype = inObject.getString("apitype");
            log.debug("解析信息-" + "apiid: " + apiid + "timestamp: " + timestamp + "	sign: " + sign + "	apitype: " + apitype);

            //  String apikey = "c5e5e59567162a6be0533228d50a17e9";
            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + custapikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);

            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!signafter.equals(sign)) {
                log.error("处理失败(sign签名错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            def customerid = inObject.getString("customerid");//华盛号
            def starttime = inObject.getString("starttime");//开始时间
            def endtime = inObject.getString("endtime");//结束时间

            log.debug("解析信息-" + "customerid: " + customerid + "starttime: " + starttime + "	endtime: " + endtime);
            // 初始化返回参数
            JSONObject result = new JSONObject();

            if (customerid!=''&&customerid!=null) {
                String q_WhereSQL1="";//-- 1 跟进信息（跟进时间、跟进一级、跟进二级、跟进备注）
                String q_WhereSQL2="";//-- 2 网聊信息（网聊时间、来访渠道、聊天时长、用户发消息行数、客服回复行数、机器人自动回复行数,系统回复）
                String q_WhereSQL22="";//--2 网聊信息 子sql
                String q_WhereSQL3="";//-- 3 通话信息（通话时间、通话时长、电话类型、话务组、）
                String q_WhereSQL4="";//-- 4 企微信息（企微添加状态、消息发送时间）
                String q_WhereSQL5="";//-- 5 活动信息（活动名称、跟进时间、参与状态、活动跟进一级、活动跟进二级、活动跟进备注）

                q_WhereSQL1="and a.customer_id='" + customerid + "'";
                q_WhereSQL2="and c.customer_id='" + customerid + "'";
                q_WhereSQL22="and c.customer_id='" + customerid + "'";
                q_WhereSQL3="and c.customer_id='" + customerid + "'";
                q_WhereSQL4="and c.customer_id='" + customerid + "'";
                q_WhereSQL5="and c.customer_id='" + customerid + "'";

                if(starttime!=null&&endtime!=null&&starttime!=""&&endtime!=""){
                    q_WhereSQL1=q_WhereSQL1+" and  a.createddate>='" + starttime + "' and a.createddate<= '" + endtime + "' order by a.createddate desc";
                    q_WhereSQL2=q_WhereSQL2+" AND cr.creation_time >= UNIX_TIMESTAMP('" + starttime + "')*1000 AND  cr.creation_time < (UNIX_TIMESTAMP( '" + endtime + "' )+86400)*1000 order by Cr.Creation_Time  desc";
                    q_WhereSQL3=q_WhereSQL3+" and  r.starttime>='" + starttime + "' and r.starttime<= '" + endtime + "' order by r.starttime desc";
                    q_WhereSQL5=q_WhereSQL5+" and  ea.updateddate>='" + starttime + "' and ea.updateddate<= '" + endtime + "' order by ea.updateddate desc";
                }else{
                    q_WhereSQL1=q_WhereSQL1+" order by a.createddate desc limit 1"
                    q_WhereSQL2=q_WhereSQL2+" order by Cr.Creation_Time  desc limit 1"
                    q_WhereSQL3=q_WhereSQL3+" order by r.starttime desc limit 1"
                    q_WhereSQL4=q_WhereSQL4+"  limit 1"
                    q_WhereSQL5=q_WhereSQL5+" order by ea.updateddate desc limit 1"
                }

                //-- 1 跟进信息（跟进时间、跟进一级、跟进二级、跟进备注）
                String queryOrderSQL1 = "select  cast(a.createddate as CHAR) as time,c.OBJECTIVESUBSTATUS_DESC as level1,b.code_name as level2,a.comment as remarks from hs_advisercallnature a left join (select Code_ID,Code_Name from c_codetables where  1=1 and Use_Type='外呼结束码二级' and Use_Status=1 order by OrderNo) b on a.advisercallnature_2=b.Code_ID left join sysc_objectivesubstatus c  on c.OBJECTIVESUBSTATUS_ID=a.advisercallnature_1 where 1=1 and CUSTOMER_GUID is not null "+q_WhereSQL1;
                log.debug("执行跟进信息查询数据SQL:" + queryOrderSQL1);

                List OrderList1 = eliteBean.chaxun_sql(queryOrderSQL1, "dataSource");
                //获取总行数
                log.debug("执行跟进信息查询数据SQL获取总条数:" + OrderList1.size());
                String reJoson1 = Util.getJsonFromList(OrderList1);
                JSONArray dataArr1 = JSONArray.parseArray(reJoson1);
                result.put("followupdata", dataArr1);

                //-- 2 网聊信息（网聊时间、来访渠道、聊天时长、用户发消息行数、客服回复行数、机器人自动回复行数,系统欢迎语回复）
                String queryOrderSQL2 = "select cr.Chat_Session_Id,cast(Date_Format(Date_Add('1970-01-01 08:00:00', Interval Cr.Creation_Time / 1000 Second), '%Y-%m-%d %H:%i:%s') as CHAR)  As requesttime,case cr.brand when '101' then '官网网站' when '102' then 'APP' when '103' then 'PC客户端' when '104' then '微信公众号' else cr.brand end as brand,Cast(Sec_To_Time(Ifnull((Cs.End_Time - Cs.Start_Time) Div 1000, 0)) As Char) as chatduration,t.custtotal,t.stafftotal,t.jqrtotal,t.xttotal from chat_request cr  Left Join ( select cm.chat_session_id as session_id,sum(case when LENGTH(cm.chat_user_id)=36 and cm.message_type=0 then 1 else 0 end) as  custtotal,sum(case when LENGTH(cm.chat_user_id)=6 and cm.message_type=0 then 1 else 0 end) as stafftotal,sum(case when LENGTH(cm.chat_user_id)=6 and cm.message_type=2 then 1 when LENGTH(cm.chat_user_id)=6 and cm.message_type=21 then 1 when LENGTH(cm.chat_user_id)=6 and cm.message_type=22 then 1 when LENGTH(cm.chat_user_id)=6 and cm.message_type=23 then 1 when LENGTH(cm.chat_user_id)=6 and cm.message_type=24 then 1 else 0 end) as xttotal, sum(case when LENGTH(cm.chat_user_id)=6 and cm.chat_user_id='BOT022' and cm.message_type=1 then 1 else 0 end) as jqrtotal from chat_message  cm left join chat_request cr on cr.chat_session_id=cm.chat_session_id and cr.request_type_id=1  Left Join Customer c  On c.Customer_Guid = Cr.client_id  where 1=1  "+q_WhereSQL22+" group by cm.chat_session_id) t  On t.Session_Id = cr.chat_session_id Left Join Chat_Session Cs  On Cs.Id = Cr.Chat_Session_Id  Left Join Customer c  On c.Customer_Guid = Cr.client_id  where 1=1 and cr.request_type_id=1 "+q_WhereSQL2;
                log.debug("执行网聊信息查询数据SQL:" + queryOrderSQL2);

                List OrderList2 = eliteBean.chaxun_sql(queryOrderSQL2, "dataSource");
                //log.debug("OrderList2:" + OrderList2);
                //获取总行数
                log.debug("执行网聊信息查询数据SQL获取总条数:" + OrderList2.size());
                String reJoson2 = Util.getJsonFromList(OrderList2);
                //log.debug("reJoson2:" + reJoson2);
                JSONArray dataArr2 = JSONArray.parseArray(reJoson2);
                //log.debug("dataArr2:" + dataArr2);
                result.put("chatdata", dataArr2);

                //-- 3 通话信息（通话时间、通话时长、电话类型、话务组、）
                String queryOrderSQL3 = "select c.customer_id,cast(r.starttime as CHAR) as starttime,cast(r.endtime as CHAR) as endtime,left (SEC_TO_TIME(TIMESTAMPDIFF(second,r.starttime,r.endtime ) ),11) as lasttime,d.calltypedescription, st.staffname,rg.ROLEGROUPDESCRIPTION as rolegroupname from record r left join C_CALLTYPE d  on r.CallType=d.CallType LEFT JOIN customer c on r.customer_guid=c.customer_guid left join staff st on r.staff_id=st.staff_ID left join rolegroup rg on   st.DEFAULTROLEGROUP=rg.ROLEGROUP_ID where 1=1 "+q_WhereSQL3;
                log.debug("执行通话信息查询数据SQL:" + queryOrderSQL3);

                List OrderList3 = eliteBean.chaxun_sql(queryOrderSQL3, "dataSource");
                //获取总行数
                log.debug("执行通话信息查询数据SQL获取总条数:" + OrderList3.size());
                String reJoson3 = Util.getJsonFromList(OrderList3);
                JSONArray dataArr3 = JSONArray.parseArray(reJoson3);
                result.put("recorddata", dataArr3);

                //-- 4 企微信息（企微添加状态、消息发送时间）
                def selectcustResult = eliteBean.chaxun_sql("select case c.WeChat_Add_Status when '2' then '已添加' when '1' then '已发送' when '0' then '未添加' ELSE c.WeChat_Add_Status  end as WeChat_Add_Status  from customer c where 1=1 "+q_WhereSQL4, "dataSource");
                def WeChat_Add_Status="";
                def msgtime="";
                if (selectcustResult.size() <= 0) {
                    WeChat_Add_Status = "";
                } else {
                    WeChat_Add_Status = selectcustResult.get(0).get("WeChat_Add_Status");
                }
                def selectWeChatResult = eliteBean.chaxun_sql("select m.tofrom,cast(m.msgtime as CHAR) as time  from hst_chat_msg m left join hst_chat_msg_receiver mr  on m.msgid=mr.msgid where 1=1 and m.tofrom='" + customerid + "' GROUP BY m.tofrom,m.msgtime union select mr.receiver,cast(m.msgtime as CHAR) as time from hst_chat_msg m  left join hst_chat_msg_receiver mr on m.msgid=mr.msgid  where 1=1 and mr.receiver='" + customerid + "' GROUP BY mr.receiver,m.msgtime ORDER BY time desc limit 1", "dataSource");
                if (selectWeChatResult.size() <= 0) {
                    msgtime = "";
                } else {
                    msgtime = selectWeChatResult.get(0).get("time");
                }
                log.debug("WeChat_Add_Status：" + WeChat_Add_Status);
                log.debug("msgtime：" + msgtime);
                def  wechatdate4="[{\"wechatstatus\":\""+WeChat_Add_Status+"\",\"time\":\""+msgtime+"\"}]";
                JSONArray dataArr4 = JSONArray.parseArray(wechatdate4);
                result.put("webchatdata", dataArr4);

                //-- 5 活动信息（活动名称、跟进时间、参与状态、活动跟进一级、活动跟进二级、活动跟进备注）
                String queryOrderSQL5 = "SELECT ha.tab_activity_name as activityname,cast(ea.updateddate as CHAR) as updateddate,cc.Code_Name as activity1,cb.Code_Name as activity2,ea.COMMENTS as remarks FROM  hst_activity ha left join elitetask_activity ea  on ha.tab_activity_id=ea.tab_activity_id left join customer c  on c.customer_id =ea.hst_no left join c_codetables cc on cc.code_id =ea.activity_state  and cc.Use_Type='活动类型父级' left join c_codetables cb on cb.code_id =ea.Activityparticulars  and cb.Use_Type='活动类型' LEFT JOIN  STAFF  s on  s.staff_id=ea.updatedby Left join c_codetables c3 on c.sq_9=c3.Code_ID and c3.Use_Type='渠道类型' where   cc.Use_Type='活动类型父级' and cb.Use_Type='活动类型'"+q_WhereSQL5;
                log.debug("执行活动信息查询数据SQL:" + queryOrderSQL5);

                List OrderList5 = eliteBean.chaxun_sql(queryOrderSQL5, "dataSource");
                //获取总行数
                log.debug("执行活动信息查询数据SQL获取总条数:" + OrderList5.size());
                String reJoson5 = Util.getJsonFromList(OrderList5);
                JSONArray dataArr5 = JSONArray.parseArray(reJoson5);
                result.put("activitydata", dataArr5);

                log.debug("result:" + result);


                endTime = System.currentTimeMillis();
                outData="{\"resultcode\":\"1\",\"resultmessage\":\"处理成功,调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+result.toString()+"}";
            }else{
                log.error("处理失败(customerid必填)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(customerid必填),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        //log.debug("开户(入金)客户信息完成返回结果:" + outData);

        return outData;
    }

}
